/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"go.uber.org/zap"
	"internal_training_be/config"
	_ "internal_training_be/db"
	"net/http"

	"github.com/spf13/cobra"
	"internal_training_be/user_mgt"
	"internal_training_be/course_signup"
	"internal_training_be/feedback"
	"internal_training_be/training_progress"
)

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start global service",
	Long:  `Start global service, including database connection, log initialization, etc.`,
	Run: func(cmd *cobra.Command, args []string) {
		log := zap.L().Sugar()

		// 获取日志读取器
		configReader, err := config.GetConfigReader()
		if err != nil {
			log.Errorf("get config reader error: %v", err)
			return
		}

		// 启动用户管理服务
		user_mgt.Run()
		
		// 启动课程报名服务
		course_signup.Run()

		// 启动课程反馈服务
		feedback.Run()

		// 启动培训进度服务
		training_progress.Run()


		// http测试
		corsMiddleware := user_mgt.EmployeeImpl{}
	
		http.Handle("/api/test", corsMiddleware.CorsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("hello world"))
		})))
		
		// 启动 HTTP 服务
		serverHost := configReader.GetString("appServe.host")
		serverPort := configReader.GetString("appServe.port")
		err = http.ListenAndServe(serverHost+":"+serverPort, nil)
		if err != nil {
			log.Errorf("http service failed to start: %s", err.Error())
		}
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)
}
